﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Utility.Extensions;
using Microsoft.IdentityModel.Tokens;

namespace CoreCms.Net.Utility.Helper
{
    /// <summary>
    /// Jwt帮助工具
    /// </summary>
    public static class JwtTokenHelper
    {
        /// <summary>
        /// 创建Token（暂不使用）
        /// </summary>
        /// <returns></returns>
        public static string CreateJwt(CoreCmsUser userInfo)
        {
            //创建声明Token数组
            var claim = new List<Claim> {
                new Claim(ClaimTypes.GivenName, userInfo.userName),
                new Claim(ClaimTypes.Name, userInfo.nickName),
                new Claim(JwtRegisteredClaimNames.Jti, userInfo.id.ToString()),
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:mm:ss")) };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yanglingcong@qq.com"));//密钥大小要超过128bt，最少要16位

            //实例化一个token对象
            //第一种方式
            //var token = new JwtSecurityToken(claims: claim);

            //第二种方式
            var token = new JwtSecurityToken(
                issuer: "kevin",//发起人：当前项目
                audience: "kevin project",//订阅：我们需要谁去使用这个Token
                claims: claim,//声明的数组
                expires: DateTime.Now.AddHours(1),//当前时间加一小时，一小时后过期
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)//数字签名 第一部分是密钥，第二部分是加密方式
            );

            //生成token
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;
        }


        /// <summary>
        /// 解析token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static GetTokenModel AnalysisToken(string token)
        {
            //第一种直接用JwtSecurityTokenHandler提供的read方法
            var jwtHander = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtSecurityToken = jwtHander.ReadJwtToken(token);

            GetTokenModel tokenModel = new GetTokenModel();
            var currentInfo = jwtSecurityToken.Claims;
            if (currentInfo.Any())
            {
                tokenModel.UserName = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.MobilePhone)!.Value;
                tokenModel.NickName = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.Name)!.Value;
                tokenModel.UserId = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.NameIdentifier)!.Value.ObjectToInt(0);

                tokenModel.Expired = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.Expired)!.Value.ObjectToInt(0);
                var dt = DateTime.Now;
                tokenModel.Expiration = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.Expiration)!.Value.ObjectToDate(dt);

                if (dt > tokenModel.Expiration)
                {
                    return null;
                }
            }
            return tokenModel;
        }
    }

    /// <summary>
    /// 获取token信息
    /// </summary>
    public class GetTokenModel
    {
        /// <summary>
        /// 用户
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 用户昵称
        /// </summary>
        public string NickName { get; set; }

        /// <summary>
        /// 用户序列
        /// </summary>
        public int UserId { get; set; }

        /// <summary>
        /// 有效时间分钟
        /// </summary>
        public int Expired { get; set; }

        /// <summary>
        /// 有效时间
        /// </summary>
        public DateTime Expiration { get; set; }


    }


}
